export const isExternal = (path: string) => {
  const reg = /^(https?:|mailto:|tel:)/
  return reg.test(path)
}

export const isArray = (arg: any) => {
  if (typeof Array.isArray === "undefined") {
    return Object.prototype.toString.call(arg) === "[object Array]"
  }
  return Array.isArray(arg)
}

export function isString(str: any) {
  if (typeof str === "string" || str instanceof String) {
    return true
  }
  return false
}

export const isValidURL = (url: string) => {
  const reg =
    /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
  return reg.test(url)
}

interface ValidationOptions {
  required?: boolean
  min?: number
  max?: number
  integer?: boolean
  positive?: boolean
  negative?: boolean
  decimal?: number
  length?: number
  message?: string
}

interface Validator {
  (rule: any, value: any, cb: (error?: Error) => void): void
}

interface ValidationRule {
  validator: Validator
  message?: string
  trigger: string
}

export function validateNumber(options: ValidationOptions = {}): ValidationRule {
  const { required, min, max, integer, positive, negative, decimal, length } = options
  const validator: Validator = (rule, value, cb) => {
    if (required && (value === undefined || value === "")) {
      cb(new Error(options.message || "该字段为必填项"))
    } else if (!value && value !== 0) {
      cb()
    } else if (isNaN(+value)) {
      cb(new Error(rule.message || "请输入数字"))
    } else if (positive && +value < 0) {
      cb(new Error(rule.message || "请输入正数"))
    } else if (negative && +value > 0) {
      cb(new Error(rule.message || "请输入负数"))
    } else if (min && +value < min) {
      cb(new Error(rule.message || `请输入大于等于${min}的数字`))
    } else if (max && +value > max) {
      cb(new Error(rule.message || `请输入小于等于${max}的数字`))
    } else if (integer && !Number.isInteger(+value)) {
      cb(new Error(rule.message || "请输入整数"))
    } else if (!integer && !Number.isFinite(+value)) {
      cb(new Error(rule.message || "请输入数字"))
    } else if (decimal && !new RegExp(`^\\d+(\\.\\d{1,${decimal}})?$`).test(value.toString())) {
      cb(new Error(rule.message || `小数点后最多保留${decimal}位`))
    } else if (length && value.toString().length > length) {
      cb(new Error(rule.message || `最大长度为${length}`))
    } else {
      cb()
    }
  }
  return {
    validator,
    message: options.message,
    trigger: "blur"
  }
}

export const commonRules = {
  requiredInput: [{ required: true, message: "该字段为必填项", trigger: "blur" }],
  requiredSelect: [{ required: true, message: "该字段为必选项", trigger: "change" }],
  requiredNot: [{ required: false }]
}
